<template>
	<view class="container">
		<!-- 输入表单 -->
		<view v-if="currentLevel === 0">
			<view v-if="!isFormCollapsed" class="form-container">
				<view class="form-item">
					<label>姓名</label>
					<input v-model="formData.name" placeholder="请输入姓名" />
				</view>
				<view class="form-item">
					<label>手机号</label>
					<input v-model="formData.phoneNumber" placeholder="请输入手机号" />
				</view>
				<view class="form-item">
					<label>年龄</label>
					<input v-model="formData.age" placeholder="请输入年龄" />
				</view>
				<view class="form-item">
					<label>职业</label>
					<picker v-model="formData.occupation" :range="occupations" @change="onOccupations">
						<view class="picker">
							{{ formData.occupation || '请选择职业' }}
						</view>
					</picker>
				</view>
				<view class="form-item">
					<label>地区</label>
					<picker mode="region" v-model="formData.address" @change="onRegionChange">
						<view class="picker">
							{{ formData.address.length > 0 ? formData.address.join(' ') : '请选择地区' }}
						</view>
					</picker>
				</view>
				<view class="form-item">
					<label>营期</label>
					<picker v-model="formData.currentSessionNumber" :range="sessionNumberOptions" @change="onSession">
						<view class="picker">
							{{ formData.currentSessionNumber || '请选择营期' }}
						</view>
					</picker>
				</view>
				<view class="form-item">
					<label>班级</label>
					<picker v-model="formData.classId" :range="classOptions" range-key="name" @change="onClassChange">
						<view class="picker">
							{{ getSelectedClassName() || '请选择班级' }}
						</view>
					</picker>
				</view>
				<view class="form-item">
					<label>大组</label>
					<picker v-model="formData.largeGroupId" :range="largeGroupsOptions" range-key="name"  @change="onLargeGroupChange"
						:disabled="formData.classId == ''">
						<view class="picker">
							{{ getSelectedtLargeGroupName() || '请选择大组' }}
						</view>
					</picker>
				</view>
				<view class="form-item">
					<label>小组</label>
					<picker v-model="formData.smallGroupId" :range="smallGroupsOptions"  range-key="name" @change="onSmallGroupChange"
						:disabled="formData.largeGroupId == ''">
						<view class="picker">
							{{ getSelectedSmallGroupName() || '请选择小组' }}
						</view>
					</picker>
				</view>
				<button @click="fetchStudents" style="width: 50%; float: left;">搜索</button>
				<button @click="cleanForm" style="width: 50%; float: left;">清空</button>
			</view>
			<!-- 展开/收起表单按钮 -->
			<button @click="toggleForm">{{ isFormCollapsed? '展开' : '收起' }}</button>
			<button @click="goSetCourse">分班</button>
		</view>
		<!-- 课程列表 -->
		<view v-if="currentLevel === 1" class="course-list">
			<view v-for="session in sessionList" class="course-item"
				@click="goToClassList(session)">
				{{ session }}. 第{{ session }}期
			</view>
		</view>
		<!-- 营期列表 -->
		<view v-if="currentLevel === 2" class="class-list">
			<view v-for="classItem in classList"  class="class-item"
				@click="goToLargeGroupList(classItem.id)">
				{{ classItem.id }}. {{ classItem.name }}
			</view>
		</view>
		<!-- 大组列表 -->
		<view v-if="currentLevel === 3" class="large-group-list">
			<view v-for="(largeGroup, index) in largeGroupList" :key="index" class="large-group-item"
				@click="goToSmallGroupList(largeGroup.id)">
				{{ index + 1 }}. {{ largeGroup.name }}
			</view>
		</view>
		<!-- 小组列表 -->
		<view v-if="currentLevel === 4" class="small-group-list">
			<view v-for="(smallGroup, index) in smallGroupList" :key="index" class="small-group-item"
				@click="saveInfo(smallGroup.id, smallGroup.name)">
				{{ index + 1 }}. {{ smallGroup.name }}
			</view>
		</view>
		<!-- 学生信息列表 -->
		<view class="student-list">
			<checkbox-group @change="checkboxChange">
				<view v-for="student in students" :key="student.students.id" class="student-item">
					<checkbox :value="student.students.id"></checkbox>
					<view class="student-info">
						<view>{{ student.students.name }}</view>
						<view>{{ student.students.age  == null ? ''  : student.students.age }}</view>
						<view>{{ student.students.phoneNumber == null ? ''  : student.students.phoneNumber }}</view>
					</view>
					<view class="student-info">
						<view>{{ student.students.address  == null ? ''  : student.students.address }}</view>
						<view>{{ student.students.occupation == null ? ''  : student.students.occupation }}</view>
					</view>
					<view class="student-info" v-for="course in student.studentCourses">
						<view>{{ course.currentSessionNumber}}期 - {{course.className}} - {{course.largeGroupName}} -
							{{course.smallGroupName}}
						</view>
					</view>
				</view>
			</checkbox-group>
		</view>
		<!-- 返回按钮 -->
		<button v-if="currentLevel > 0" @click="goBack">返回</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				students: [],
				currentLevel: 0,
				classList: [{
						id: 1,
						name: '格物班'
					},
					{
						id: 2,
						name: '致知班'
					},
					{
						id: 3,
						name: '正心班'
					},
					{
						id: 4,
						name: '诚意班'
					}
				],
				classOptions: [{
						id: 1,
						name: '格物班'
					},
					{
						id: 2,
						name: '致知班'
					},
					{
						id: 3,
						name: '正心班'
					},
					{
						id: 4,
						name: '诚意班'
					}
				],
				sessionNumberOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
				sessionList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
				largeGroupsOptions: [],
				smallGroupsOptions: [],
				largeGroupList: [],
				smallGroupList: [],
				selectedStudentIds: [],
				selectedSessionId: null,
				selectedClassId: null,
				selectedLargeGroupId: null,
				occupations: ['农、林、牧、渔业', ' 采矿业', '制造业', '电力、热力、燃气及水生产和供应业', '建筑业', '批发和零售业', '交通运输、仓储和邮政业',
					'住宿和餐饮业 ', '信息传输、软件和信息技术服务业', '金融业', '房地产业', '租赁和商务服务业', '科学研究和技术服务业',
					'水利、环境和公共设施管理业', '居民服务、修理和其他服务业', '教育', '卫生和社会工作 ', '文化、体育和娱乐业 ', '公共管理、社会保障和社会组织',
					'国际组织', '学生', '其他'
				],

				formData: {
					address: [],
					occupation: '',
					name: '',
					phoneNumber: '',
					age: '',
					currentSessionNumber: '',
					classId: '',
					largeGroupId: '',
					smallGroupId: ''
				},
				isFormCollapsed: false
			};
		},
		onLoad() {
			this.fetchStudents();
		},
		methods: {
			onSession(e) {
				this.formData.currentSessionNumber = this.sessionNumberOptions[e.detail.value]
			},
			onClassChange(e) {
				const selectedIndex = e.detail.value;
				this.formData.classId = this.classOptions[selectedIndex].id;
				console.log(this.classOptions[selectedIndex].id)
				this.formData.largeGroupId=''
				this.formData.smallGroupId=''
				uni.request({
					url: 'http://localhost:9090/user/getResource',
					method: 'POST',
					data: {
						parentId : this.formData.classId,
						level : 2
					},
					success: (res) => {
						this.largeGroupsOptions = res.data.data
					},
					fail: (err) => {
						console.error('获取资源失败:', err);
					}
				});
			},
			getSelectedClassName() {
				const selectedOption = this.classOptions.find(item => item.id === this.formData.classId);
				return selectedOption ? selectedOption.name : null;
			},
			onLargeGroupChange(e) {
				this.formData.largeGroupId = this.largeGroupsOptions[e.detail.value].id
				this.formData.smallGroupId=''
				uni.request({
					url: 'http://localhost:9090/user/getResource',
					method: 'POST',
					data: {
						parentId : this.formData.largeGroupId,
						level: 3
					},
					success: (res) => {
						this.smallGroupsOptions = res.data.data 
					},
					fail: (err) => {
						console.error('获取资源失败:', err);
					}
				});
				
			},
			getSelectedtLargeGroupName() {
				const selectedOption = this.largeGroupsOptions.find(item => item.id === this.formData.largeGroupId.toString());
				return selectedOption ? selectedOption.name : null;
			},
			onSmallGroupChange(e) {
				this.formData.smallGroupId = this.smallGroupsOptions[e.detail.value].id
			},
			getSelectedSmallGroupName() {
				const selectedOption = this.smallGroupsOptions.find(item => item.id === this.formData.smallGroupId.toString());
				return selectedOption ? selectedOption.name : null;
			},
			// 获取学生信息
			fetchStudents() {
				this.students = []
				uni.request({
					url: 'http://localhost:9090/user/getStudents',
					method: 'POST',
					data: {
						name: this.formData.name,
						phoneNumber: this.formData.phoneNumber,
						occupation: this.formData.occupation,
						age: this.formData.age,
						address: this.formData.address.toString(),
						currentSessionNumber: this.formData.currentSessionNumber,
						classId: this.formData.classId,
						largeGroupId: this.formData.largeGroupId,
						smallGroupId: this.formData.smallGroupId 
					},
					success: (res) => {
						this.selectedStudentIds = []
						this.students = res.data.data;
					},
					fail: (err) => {
						console.error('获取学生信息失败:', err);
					}
				});
			},
			addIds(studentId) {
				const index = this.selectedStudentIds.indexOf(studentId);
				if (index > -1) {
					// 如果存在，从数组中移除
					this.selectedStudentIds.splice(index, 1);
				} else {
					// 如果不存在，添加到数组中
					this.selectedStudentIds.push(studentId);
				}
			},
			// 进入设置页面
			goToSettings() {
				// 这里可以根据需求做更多处理，比如将选中的学生 ID 传递给后续操作
				this.currentLevel = 1;
			},
			goSetCourse() {
				if (this.selectedStudentIds.length === 0) {
					uni.showToast({
						title: '请先选择学员',
						icon: 'none'
					});
					return;
				} else {
					this.currentLevel = 1;
				}
			},
			cleanForm() {
				this.formData = {
					address: [],
					occupation: '',
					name: '',
					phoneNumber: '',
					age: '',
					currentSessionNumber: '',
					classId: '',
					largeGroupId: '',
					smallGroupId: ''
				}
			},
			// 进入班级列表
			async goToClassList(sessionId) {
				this.selectedSessionId = sessionId;
				this.currentLevel = 2;
			},
			checkboxChange(e) {
				this.selectedStudentIds = e.detail.value
			},
			// 进入大组列表
			async goToLargeGroupList(classId) {
				
				this.selectedClassId = classId;
				this.getResource(classId, 2);
				this.currentLevel = 3;
			},
			// 进入小组列表
			async goToSmallGroupList(largeGroupId) {
				this.selectedLargeGroupId = largeGroupId;
				this.getResource(largeGroupId, 3);
				this.currentLevel = 4;
			},
			// 保存信息并打印
			saveInfo(smallGroupId, smallGroupName) {
				console.log(this.selectedSessionId)
				uni.showModal({
					title: '确认保存',
					content: '是否确认保存该信息？',
					success: (res) => {
						if (res.confirm) {
							const savedInfo = {
								studentId: this.selectedStudentIds.toString(),
								classId: this.selectedClassId,
								className: this.getClassById(this.selectedClassId).name,
								currentSessionNumber: this.selectedSessionId,
								largeGroupId: this.selectedLargeGroupId,
								largeGroupName: this.getLargeGroupById(this.selectedLargeGroupId).name,
								smallGroupId: smallGroupId,
								smallGroupName: smallGroupName
							};
							uni.request({
								url: 'http://localhost:9090/user/setCourse',
								method: 'POST',
								data: savedInfo,
								success: (res) => {
									uni.showToast({
										title: '分班成功',
										icon: 'none'
									});
									this.fetchStudents()
									this.currentLevel = 0;
								}
							});

						}
					}
				});
			},
			// 根据id获取课程信息
			getCourseById(id) {
				return this.courseList.find(item => item.id === id);
			},
			// 根据id获取班级信息
			getClassById(id) {
				return this.classList.find(item => item.id === id);
			},
			// 根据id获取大组信息
			getLargeGroupById(id) {
				return this.largeGroupList.find(item => item.id === id);
			},
			// 返回上一层
			goBack() {
				this.selectedStudentIds = []
				this.currentLevel--;
			},
			// 获取资源
			getResource(parentId, level) {
				uni.request({
					url: 'http://localhost:9090/user/getResource',
					method: 'POST',
					data: {
						parentId,
						level
					},
					success: (res) => {
						if (level === 1) {
							this.classList = res.data.data;
						} else if (level === 2) {
							this.largeGroupList = res.data.data;
						} else {
							this.smallGroupList = res.data.data;
						}
					},
					fail: (err) => {
						console.error('获取资源失败:', err);
					}
				});
			},
			// 地区选择器改变事件
			onRegionChange(e) {
				this.formData.address = e.detail.value;
				this.$forceUpdate();
			},
			onOccupations(e) {
				this.formData.occupation = this.occupations[e.detail.value];
			},
			// 展开/收起表单
			toggleForm() {
				this.isFormCollapsed = !this.isFormCollapsed;
			}
		}
	};
</script>

<style scoped>
	.container {
		padding: 20px;
	}

	.form-container {
		margin-bottom: 20px;
	}

	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
	}

	.form-item label {
		width: 80px;
	}

	input {
		flex: 1;
		padding: 10px;
		border: 1px solid #ccc;
		margin-right: 10px;
	}

	button {
		padding: 10px 20px;
		margin-bottom: 10px;
	}

	.student-list,
	.course-list,
	.class-list,
	.large-group-list,
	.small-group-list {
		margin-top: 20px;
	}

	.student-item {
		padding: 10px;
		border: 1px solid #ccc;
		margin-bottom: 10px;
		align-items: center;
	}

	.student-info {
		display: flex;
		justify-content: space-around;
		flex: 1;
		/* 可以根据需要调整元素之间的间距 */
	}

	.course-item,
	.class-item,
	.large-group-item,
	.small-group-item {
		padding: 10px;
		border: 1px solid #ccc;
		margin-bottom: 10px;
		cursor: pointer;
	}
</style>